import React, { useState, useEffect, useRef, useCallback } from 'react'
import { Dialog, DialogContent, DialogTrigger } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import ImageSliceViewer, {
  ImageSliceGrid,
  type PositionData
} from '@/components/ui/image-slice-viewer'

interface ImageSliceData {
  id: string
  x: number
  y: number
  width: number
  height: number
  name: string
}

interface ImagePickerProps {
  onImageSelect: (imageName: string) => void
  trigger?: React.ReactNode
  imageUrl?: string
  sliceData?: ImageSliceData[]
  className?: string
}

export default function ImagePicker({
  onImageSelect,
  trigger,
  imageUrl = '',
  sliceData = [],
  className = ''
}: ImagePickerProps) {
  const [open, setOpen] = useState(false)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [sliceImages, setSliceImages] = useState<{ [key: string]: string }>({})

  // 切割图片
  const extractImages = useCallback(async () => {
    if (!imageUrl || sliceData.length === 0) return

    const canvas = canvasRef.current
    if (!canvas) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    const img = new Image()
    img.crossOrigin = 'anonymous'

    img.onload = () => {
      const extractedImages: { [key: string]: string } = {}

      sliceData.forEach((slice) => {
        // 设置 canvas 尺寸为单个切片的尺寸
        canvas.width = slice.width
        canvas.height = slice.height

        // 清空 canvas
        ctx.clearRect(0, 0, slice.width, slice.height)

        // 从大图中切出对应位置的小图
        ctx.drawImage(
          img,
          slice.x,
          slice.y,
          slice.width,
          slice.height, // 源图片的位置和尺寸
          0,
          0,
          slice.width,
          slice.height // 目标 canvas 的位置和尺寸
        )

        // 将切出的图片转换为 base64
        extractedImages[slice.id] = canvas.toDataURL('image/png')
      })

      setSliceImages(extractedImages)
    }

    img.onerror = () => {
      console.error('Failed to load image')
    }

    img.src = imageUrl
  }, [imageUrl, sliceData])

  useEffect(() => {
    extractImages()
  }, [extractImages])

  const handleImageClick = (slice: ImageSliceData) => {
    onImageSelect(slice.name)
    setOpen(false)
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {trigger || (
          <Button variant="outline" className={className}>
            选择图片
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="max-h-[80vh] max-w-2xl">
        <div className="space-y-4">
          <div className="text-center">
            <h3 className="text-lg font-semibold">选择图片</h3>
            <p className="text-sm text-gray-600">点击图片进行选择</p>
          </div>

          <ScrollArea className="h-96">
            <div className="grid grid-cols-6 gap-2 p-2">
              {sliceData.map((slice) => (
                <div
                  key={slice.id}
                  className="flex size-16 cursor-pointer items-center justify-center rounded border border-gray-200 bg-white transition-colors hover:border-blue-500 hover:bg-blue-50"
                  onClick={() => handleImageClick(slice)}
                  title={slice.name}
                >
                  {sliceImages[slice.id] ? (
                    <img
                      src={sliceImages[slice.id]}
                      alt={slice.name}
                      className="size-full object-contain"
                    />
                  ) : (
                    <div className="flex size-full items-center justify-center rounded bg-gray-100 text-xs text-gray-500">
                      加载中...
                    </div>
                  )}
                </div>
              ))}
            </div>
          </ScrollArea>

          {sliceData.length === 0 && (
            <div className="py-8 text-center text-gray-500">
              <p>没有可用的图片切片</p>
              <p className="text-sm">请先使用图片切割工具生成切片数据</p>
            </div>
          )}
        </div>

        {/* 隐藏的 canvas 用于图片处理 */}
        <canvas ref={canvasRef} className="hidden" />
      </DialogContent>
    </Dialog>
  )
}

// 新增：图床图片选择组件
interface ImageBedPickerProps {
  imageBedId: string // 图床ID，如"14100"
  onImageSelect: (imageSliceId: string) => void // 返回格式: "14100_2_4"
  trigger?: React.ReactNode
  className?: string
  title?: string // 按钮显示的文本
}

export function ImageBedPicker({
  imageBedId,
  onImageSelect,
  trigger,
  className = '',
  title = '选择图床图片2' // 默认值
}: ImageBedPickerProps) {
  const [open, setOpen] = useState(false)

  const handleOpenChange = (newOpen: boolean) => {
    setOpen(newOpen)
  }

  // 生成5x5网格的所有位置数据
  const positions = Array.from({ length: 25 }, (_, index) => {
    const row = Math.floor(index / 5)
    const col = index % 5
    return {
      row,
      col,
      id: `${row}-${col}`,
      name: `(${row},${col})`
    } as PositionData
  })

  const handlePositionClick = (position: PositionData) => {
    const imageSliceId = `${imageBedId}_${position.row}_${position.col}`
    onImageSelect(imageSliceId)
    handleOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        {trigger || (
          <Button variant="outline" className={className}>
            {title}
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="max-w-2xl">
        <div className="space-y-4">
          <div className="flex justify-center">
            <ImageSliceGrid
              imageId={imageBedId}
              positions={positions}
              className="grid-cols-5 gap-2"
              itemClassName="border rounded-lg hover:shadow-md transition-all"
              showLabels={true}
              onItemClick={handlePositionClick}
            />
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
